<template>
  <section class="course-item" 
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <!-- 头部   -->
    <div class="header">
      <el-page-header @back="goBack" :content="courseTitle"></el-page-header>
      <el-button type="primary" @click="handleSave('form')" >保存</el-button>
    </div>
    <!-- 表单 -->
    <el-form 
    ref="form" 
    :model="course" 
    label-width="120px" 
    :rules="rules">
      <!-- 基本信息 -->
      <el-card class="box-card">
        <div slot="header">
          <span>基本信息</span>
        </div>
        <el-form-item label="名称" prop="course_name">
          <el-input
            type="text"
            placeholder="请输入课程名称"
            maxlength="50"
            show-word-limit
            v-model="course.course_name"
          ></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="brief">
          <el-input
            type="text"
            placeholder="请输入课程简介"
            maxlength="100"
            show-word-limit
            v-model="course.brief"
          ></el-input>
        </el-form-item>
        <el-form-item label="讲师名称" prop="teacher_name">
          <el-input
            type="text"
            placeholder="请输入讲师名称"
            maxlength="50"
            show-word-limit
            v-model="course.teacher_name"
          ></el-input>
        </el-form-item>
        <el-form-item label="讲师简介">
          <el-input
            type="text"
            placeholder="请输入讲师简介"
            maxlength="100"
            show-word-limit
            v-model="course.teacher_info"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程概述" prop="preview_first_field" >
          <el-col :span="11">
            <el-input
              type="text"
              placeholder="请输入课程概述1"
              maxlength="20"
              show-word-limit
               v-model="course.preview_first_field"
            ></el-input>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-input
              type="text"
              placeholder="请输入课程概述2"
              maxlength="20"
              show-word-limit
              v-model="course.preview_second_field"
            ></el-input>
          </el-col>
        </el-form-item>
      </el-card>
      <!-- 销售信息 -->
      <el-card class="box-card">
        <div slot="header">
          <span>销售信息</span>
        </div>
        <el-form-item label="售卖价格">
          <el-input
            type="number"
            placeholder="请输入售卖价格"
            :min="0" oninput="if(value<0)value=0"
            v-model="course.discounts"
          > <template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="商品原价">
          <el-input
            type="number"
            placeholder="请输入商品原价"
            :min="0" oninput="if(value<0)value=0"
            v-model="course.price"
          > <template slot="append">元</template></el-input>
        </el-form-item>
         <el-form-item label="活动标签">
          <el-input
            type="text"
            placeholder="请输入活动标签"
            maxlength="4"
            show-word-limit
             v-model="course.price_tag"
          ></el-input>
        </el-form-item>
      </el-card>
      <!-- 分享信息 -->
      <el-card  class="box-card">
        <div slot="header">
          <span>分享信息</span>
        </div>
        <el-form-item label="分享小图" prop="share_image_title">
            <el-input type="text" placeholder="图片介绍" v-model="course.share_image_title">
                <el-upload 
                slot="prepend"
                action
                :auto-upload="false"
                :on-change="onchange"
                > 
                   <el-button type="primary" size="small">点击上传</el-button>
                </el-upload>
            </el-input>
        </el-form-item>
         <el-form-item label="分享标题" prop="share_title">
          <el-input
            type="text"
            placeholder="请输入分享标题"
            maxlength="40"
            show-word-limit
             v-model="course.share_title"
          ></el-input>
        </el-form-item>
         <el-form-item label="分享简介" prop="share_description">
          <el-input
            type="text"
            placeholder="请输入分享简介"
            maxlength="60"
            show-word-limit
             v-model="course.share_description"
          ></el-input>
        </el-form-item>
      </el-card>
      <!-- 富文本 -->
      <el-card  class="box-card">
        <editor v-model="course.course_description"></editor>
      </el-card>
    </el-form>
  </section>
</template>

<script>
import Editor from '@/components/Editor'
import {axios} from '../utils';
export default {
  data: function () {
    return {
      courseTitle:"新增课程",
       course: {
        course_name: "", // 课程名称
        brief: "", // 课程简介
        teacher_name: "", // 讲师名称
        teacher_info: "", // 讲师简介
        preview_first_field: "", // 第一个课程概述
        preview_second_field: "", // 第二个课程概述
        discounts: 0 , // 课程实际售卖价格
        price: 0, // 课程原价
        price_tag: "", // 活动标签
        share_image_title: "", // 分享小图的说明
        share_title: "", // 分享标题
        share_description: "", // 分享简介
        course_description: "", // 课程详情
      },
      params:{}, //保存时传给后端的参数
      loading:false
      ,
      rules:{
        course_name: [
          //trigger:blur鼠标移出输入框的时候校验
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
          ],
          brief: [
          { required: true, message: "请输入课程简介", trigger: "change" },
          {
            min: 5,
            max: 100,
            message: "长度在 5 到 100 个字符",
            trigger: "blur",
          },
        ],
        teacher_name: [
          { required: true, message: "请输入讲师姓名", trigger: "change" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        preview_first_field: [
          { required: true, message: "请输入课程概述", trigger: "change" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        share_title: [
          { required: true, message: "请输入分享标题", trigger: "change" },
        ],
        share_description: [
          { required: true, message: "请输入分享简介", trigger: "change" },
        ],
      }

      
    };
  },
  created() {

    

    console.log("获取的couseId=",this.$route.params.courseId);
    //取出id
    const id=this.$route.params.courseId
    if(!id)
    {
      return this.redirectToError()
    }

    if(id==="new")
    {
      this.courseTitle="新增课程"
      this.$breadcrumbs = [
      { name: "Course", text: "课程管理" },
      { text: "新增课程" },
    ];
    }
    else
    {
      this.courseTitle="营销信息"
      this.$breadcrumbs = [
      { name: "Course", text: "课程管理" },
      { text: "营销信息" },
    ];
      //加载课程信息
      this.loadCourse(id)
    }

    // 组件加载或创建的时候，需要创建一个FormData的实例，以便传递图片或者文件
    this.params=new FormData();
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    // 保存课程信息
    handleSave(formName) {
    //设置Content-type为多部件上传
    

       this.$refs[formName].validate((valid) => {
        if (valid) {
          //验证通过的逻辑
          console.log("验证通过");
          let config={
            headers:{
              "Content-Type":"multipart/form-data"
            }
          }
          this.loading=true
          //获取表单中的数据，保存到params中（params就是上面Content-type要求的多部件的FormData对象）
          for(const key in this.course)
          {
              // this.params[key]=this.course[key]
              this.params.append(key,this.course[key])         }

          console.log("params的内容",JSON.parse(JSON.stringify(this.params)));
          //将收集到的课程信息params按照接口约定传给后端
          axios.post("/courseSalesInfo", this.params, config).then((res) => {
          console.log("保存课程信息的结果：", res);
          if(res.data.status === 0)
          {
            this.$router.back()
          }
          else if(res.data.status != 0)
          {{
              this.$message({
                type:"error",
                message:res.data.msg
              })
          }
          }
          this.loading=false
        }).catch((err)=>{
          // 验证不通过
          this.$message({
                type:"error",
                message:err.message
              })
            this.loading=false    
        });
        } 
      })
    },
    //upload组件文件上传的回调
    onchange(file)
    {
      console.log("上传的文件",JSON.parse(JSON.stringify(file)));
      if(file != null)
      this.params.append("file",file.raw,file.name)
    },
    //传送到错误页面
    redirectToError()
    {
      this.$router.replace({path:"no_fondId"})
    },
    //加载课程信息
    loadCourse(id)
    {
      this.loading=true
        axios.get("/course",{
          params:{
            methodName:"findCourseById",
            id
          }
        }).then((res)=>{
          console.log("${id}查询到的课程",JSON.parse(JSON.stringify(res)));
          this.course=res.data
          this.loading=false
        }).catch((error)=>{
          this.$message.console.error("数据显示失败");
          this.loading=false
        })
    }
  },
  components:{
      Editor
  },
};
</script>

<style>
.course-item .header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.course-item .box-card {
  margin-top: 25px;
}
</style>